package main;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import plugins.PluginModule;


public class Room extends Thread {
   
   /**
    * List of currently active ServerThreads (sockets)
    */
   public List<User> users;
   private PluginModule plugins;
   
   public Room(String name) throws IOException {
   	super(name);
      users = new ArrayList<User>();
      plugins = new PluginModule();
   }

   /**
    * Dispatches a chat message to everyone
    */
   public void dispatchChatMsg(User sender, String msg) {
      System.out.println("[" + sender.name + "] " + msg);
      dispatchMsg("[" + sender.name + "] " + msg);
   }
   
   /**
    * Dispatches a message to everyone
    */
   public void dispatchMsg(String msg) {
      for (User st : users) {
         st.dispatch(msg);
      }
   }
   
   /**
    * Dispatches a message to everyone exept the exclude
    */
   public void dispatchMsg(String msg, User exclude) {
      for (User st : users) {
         if (exclude == st) continue;
         st.dispatch(msg);
      }
   }
   
   /**
    * Dispatches a room message only for the target client
    */
   public void dispatchRoomMsg(User target, String msg) {
      target.dispatch(Messages.ROOM + " " + msg);
   }
   
   /**
    * Dispatches a global room message for everyone to see
    */
   public void dispatchRoomMsg(String msg) {
      dispatchMsg(Messages.ROOM + " " + msg);
   }
   
   public User getUserByName(String name) {
      for (User user : users) {
         if (user.name.equals(name)) {
            return user;
         }
      }
      return null;
   }

   /**
    * Returns the Plugins instance
    */
   public PluginModule getPlugins() {
      return plugins;
   }
   
   /**
    * Adds a thread to the socket list
    */
   public void addUser(User user) {
      dispatchRoomMsg(Messages.joinedRoom(user.name));
      users.add(user);
   }
   
   /**
    * Removes a thread from the socket list
    */
   public void removeUser(User user) {
      dispatchRoomMsg(Messages.leftRoom(user.name));
      users.remove(user);
      user = null;
   }
   
   public void kickUser(User user) {
      dispatchRoomMsg(Messages.hasBeenKicked(user.name));
      users.remove(user);
      user.close();
      user = null;
   }

   @Override
   public String toString() {
      return "Room [" + users + "]";
   }

}
